package cn.dmoncat.util.influx;

import cn.dmoncat.util.influx.config.InfluxProperties;
import com.influxdb.client.InfluxDBClient;
import com.influxdb.client.write.Point;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * InfluxDB 工具
 *
 * @see  "https://docs.influxdata.com/influxdb/v2/"
 *
 * @author 延晓磊
 * @since 2024年07月02日
 */
@Component
public class InfluxUtil {

    // DB配置
    @Resource
    private InfluxProperties influxProperties;
    // DB连接
    @Resource
    public InfluxDBClient influxDBClient;

    /**
     * 保存
     *
     * @param o 数据，参考MeasurementMapper注解
     */
    public void save(Object o){
        if (o != null) {
            // 映射
            MeasurementMapper mapper = MeasurementMapper.get(o.getClass());
            // 转换
            Point point = mapper.toPoint(o);
            // 写入
            influxDBClient.getWriteApiBlocking().writePoint(point);
        }
    }

    /**
     * 保存
     *
     * @param os 数据，参考MeasurementMapper注解
     */
    public void save(List<?> os){
        if (os != null && os.size() > 0) {
            // 映射
            MeasurementMapper mapper = MeasurementMapper.get(os.get(0).getClass());
            // 转换
            List<Point> points = mapper.toPoints(os);
            // 写入
            influxDBClient.getWriteApiBlocking().writePoints(points);
        }
    }

}
